package com.jagochan.module.business.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jagochan.common.result.ResultUtils;
import com.jagochan.common.result.ResultVo;
import com.jagochan.module.business.pojo.po.Topic;
import com.jagochan.module.business.pojo.vo.TopicPageVO;
import com.jagochan.module.business.service.TopicService;
import com.jagochan.module.rbac.common.exception.BusinessException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Validated
@Tag(name = "话题")
@RequiredArgsConstructor
@RequestMapping("/community/topic")
@RestController
public class TopicController {

    private final TopicService topicService;

    @Operation(summary = "获取指定分类下的话题列表")
    @GetMapping("/page")
    public ResultVo<TopicPageVO> pageTopic(@Parameter(description = "话题分类ID", example = "8") @Min(value = 1L, message = "分类ID不能小于1")
                                           Long categoryId,
                                           @Parameter(description = "分页参数（页码）", example = "1") @Min(value = 1L, message = "页码不能小于1") @Max(value = 100L, message = "页码不能大于100")
                                           int pageNo) {
        Page<Topic> page = Page.of(pageNo, 10);
        page = topicService.lambdaQuery()
                .eq(Topic::getCategoryId, categoryId) // 查询指定分类下的话题
                .page(page); // 分页查询

        return ResultUtils.success("查询成功", TopicPageVO.builder()
                .total(page.getTotal())
                .pageSize(page.getSize())
                .currentPage(page.getCurrent())
                .lastPage(page.getPages())
                .list(page.getRecords())
                .build());
    }

    @Operation(summary = "根据ID查询话题详情")
    @GetMapping("/get-topic-detail")
    public ResultVo<Topic> getTopicDetail(@Parameter(description = "话题ID", example = "2") @Min(value = 1L, message = "话题ID不能小于1") Long id) {
        Topic topic = topicService.getById(id);
        if (Objects.isNull(topic)) {
            return BusinessException.raise("ID为【" + id + "】的话题不存在");
        }
        return ResultUtils.success("查询成功", topic);
    }

}